package com.example.javaservice.controller;

import com.example.javaservice.common.Result;
import com.example.javaservice.pojo.User;
import com.example.javaservice.security.JwtUtil;
import com.example.javaservice.service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class UserController {
    private final UserService userService;
    private final String baseUrl = "http://localhost:8080";
    public UserController(UserService userService) {
        this.userService = userService;
    }

    /** 注册 */
    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) {
        boolean success = userService.register(user);
        if (success) {
            return Result.success("注册成功");
        } else {
            return Result.error("用户名已存在");
        }
    }


    /** 登录 */
    @PostMapping("/login")
    public Result<?> login(@RequestBody User user) {
        User loginUser = userService.login(user.getUsername(), user.getPassword());
        if (loginUser != null) {
            String token = JwtUtil.generateToken(loginUser.getUsername(), loginUser.getRole());

            // ✅ 把用户所有字段一起返回给前端
            Map<String, Object> data = new HashMap<>();
            data.put("id", loginUser.getId());
            data.put("username", loginUser.getUsername());
            data.put("nickname", loginUser.getNickname());
            data.put("avatarUrl", baseUrl+loginUser.getAvatar());
            data.put("email", loginUser.getEmail());
            data.put("role", loginUser.getRole());
            data.put("token", token);

            return Result.success("登录成功", data);
        } else {
            return Result.error(401, "用户名或密码错误");
        }
    }


}
